import {reqCode,reqRegister,reqLogin,reqUserInfo,reqlogout} from '@/api'
import { setToken,getToken,clearToken } from '@/utils/token'
const state = {
    code:'',
    token:getToken(),
    userInfo:{}
}
const mutations = {
    GETCODE(state,code){
        state.code = code
    },
    USERLOGIN(state,token){
        state.token = token
    },
    GETUSERINFO(state,userInfo){
        state.userInfo = userInfo
    },
    GETLOGOUT(state){
        state.token = '',
        state.userInfo = {},
        clearToken();

    }
}
const actions = {
   async getCode({commit},phone){
        let result = await reqCode(phone)
        
        if(result.code==200){
            commit('GETCODE',result.data)
            return 'ok'
        }else{
            return Promise.reject(new Error('faile'))
        }
    },
   async register({commit},{phone,password,code}){
        let result =await reqRegister(phone,password,code)
        if(result.code==200){
            return 'ok'
        }else{
            return Promise.reject(result.message)
        }
    },
   async userLogin({commit},{phone,password}){
       let result = await reqLogin(phone,password)
       
      
       if(result.code==200){
        //如果仓库,已经存储token,用户一定是登陆了
        commit("USERLOGIN",result.data.token);
        setToken(result.data.token)
        return 'ok';
    }else{
        //登录失败
        return Promise.reject(result.message);
    }
  
    },
    // 获取用户信息
   async getUserInfo({commit}){
       let result =await reqUserInfo()
      
       if(result.code==200){
           commit('GETUSERINFO',result.data)
           return 'ok'
       }else{
           return Promise.reject(new Error('faile'))
       }
    },
    //退出登录
  async getlogout({commit}){
       let result =await reqlogout()
       if(result.code==200){
           commit('GETLOGOUT')
       }
    }
}
const getters ={}
export default {
    state,
    mutations,
    actions,
    getters
}